package com.sdkj.fixed.asset.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import com.sdkj.fixed.asset.common.exception.FileUploadNotFinishException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service
public class QiniuService {

    private static final Logger logger = LoggerFactory.getLogger(QiniuService.class);

    // 设置好账号的ACCESS_KEY和SECRET_KEY
    private String ACCESS_KEY = "8m8pzXMjK2BCbh3cxXYurFrV9fHAkxa5nG3p929B";
    private String SECRET_KEY = "AdT1QuHPkI0dhqnOzGCoLmjzh0RwwKFdtQ5_uh3y";
    // 要上传的空间
    private String bucketname = "sdkeji";

    // 密钥配置
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
//    // 构造一个带指定Zone对象的配置类,不同的七云牛存储区域调用不同的zone
//    Configuration cfg = new Configuration(Zone.zone1());

    //构造一个带指定Region对象的配置类
    Configuration cfg = new Configuration(Region.region0());
    // ...其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);

    //
    private static String QINIU_IMAGE_DOMAIN = "qiniucdn.shengdianshiji.com/";

    // 简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken() {
        return auth.uploadToken(bucketname);
    }


    public String saveImage(MultipartFile file, String fileName) throws IOException {
        try {
            // 调用put方法上传
            Response res = uploadManager.put(file.getBytes(), fileName, getUpToken());
            // 打印返回的信息
            if (res.isOK() && res.isJson()) {
                // 返回这张存储照片的地址
                return QINIU_IMAGE_DOMAIN + JSONObject.parseObject(res.bodyString()).get("key");
            } else {
                logger.error("七牛异常:" + res.bodyString());
                return null;
            }
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            logger.error("七牛异常:" + e.getMessage());
            return null;
        }
    }

    public String ueditorSaveImage(MultipartFile file) throws IOException {
        try {
            int dotPos = file.getOriginalFilename().lastIndexOf(".");
            if (dotPos < 0) {
                return null;
            }
            String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
            // 判断是否是合法的文件后缀
//            if (!FileUtil.isFileAllowed(fileExt)) {
//                return null;
//            }

            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
            // 调用put方法上传
            Response res = uploadManager.put(file.getBytes(), fileName, getUpToken());
            // 打印返回的信息
            if (res.isOK() && res.isJson()) {
                // 返回这张存储照片的地址
                return "" + JSONObject.parseObject(res.bodyString()).get("key");
            } else {
                logger.error("七牛异常:" + res.bodyString());
                return null;
            }
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            logger.error("七牛异常:" + e.getMessage());
            return null;
        }
    }

    public static void download() {
        String fileName = "jinma_d402f58aaf2f4579a16a6c2a16bc988d.txt";
        String domainOfBucket = "http://qiniucdn.shengdianshiji.com/";
        String publicUrl = String.format("%s/%s", domainOfBucket, fileName);
        String ACCESS_KEY = "8m8pzXMjK2BCbh3cxXYurFrV9fHAkxa5nG3p929B";
        String SECRET_KEY = "AdT1QuHPkI0dhqnOzGCoLmjzh0RwwKFdtQ5_uh3y";
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        long expireInSeconds = 3600;//1小时，可以自定义链接过期时间
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
        System.out.println(finalUrl);
    }


//    public static void xxx() {
//        String ACCESS_KEY = "8m8pzXMjK2BCbh3cxXYurFrV9fHAkxa5nG3p929B";
//        String SECRET_KEY = "AdT1QuHPkI0dhqnOzGCoLmjzh0RwwKFdtQ5_uh3y";
//        String bucket = "sdkeji";
//        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
//
//        auth.uploadToken(bucket, key, 3600, new StringMap()
//                .put("callbackUrl", "callbackurl")
//                .put("callbackBody", "{"filename":""));
//    }

    public static void checkFile(String filePath) throws FileUploadNotFinishException {
        Configuration cfg = new Configuration(Region.region0());
//...其他参数参考类注释
//        private String ACCESS_KEY = "8m8pzXMjK2BCbh3cxXYurFrV9fHAkxa5nG3p929B";
////        private String SECRET_KEY = "AdT1QuHPkI0dhqnOzGCoLmjzh0RwwKFdtQ5_uh3y";
////        // 要上传的空间
////        private String bucketname = "sdkeji";
        String accessKey = "8m8pzXMjK2BCbh3cxXYurFrV9fHAkxa5nG3p929B";
        String secretKey = "AdT1QuHPkI0dhqnOzGCoLmjzh0RwwKFdtQ5_uh3y";
        String bucket = "sdkeji";
        String key = filePath.split("/")[1];
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        System.out.println("11111");
        try {
            FileInfo fileInfo = bucketManager.stat(bucket, key);
            logger.info("hash:       " + fileInfo.hash);
            logger.info("fsize:      " + fileInfo.fsize);
            logger.info("mimeType:   " + fileInfo.mimeType);
            logger.info("putTime:    " + fileInfo.putTime);
        } catch (QiniuException ex) {
            logger.error(ex.response.toString());
            throw new FileUploadNotFinishException("文件上传中请稍侯");
        }
    }

    public static void main(String[] args) {
        checkFile("qiniucdn.shengdianshiji.com/jinma_002577f370994fc69d0fef5ac3dc9e85.xlsx");
//        download();
    }
}
